package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	_ "gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type PmsCategory struct {
	CatId        uint32 `json:"catId" gorm:"cat_id"`
	Name         string `json:"name" gorm:"name"`
	ParentCid    uint32 `json:"parentCid" gorm:"parent_cid"`
	CatLevel     uint   `json:"catlevel" gorm:"cat_level"`
	ShowStatus   uint   `json:"showStatus" gorm:"show_status"`
	Sort         uint   `json:"sort" gorm:"sort"`
	Icon         string `json:"icon" gorm:"icon"`
	ProductUnit  string `json:"productUnit" gorm:"product_unit"`
	ProductCount uint   `json:"productCount" gorm:"product_count"`
}

func main() {

	mysqlConfig := mysql.Config{
		DSN:                       `root:!QAZ2wsx@tcp(60.205.194.87:3306)/gulimall?charset=utf8mb4&parseTime=True&loc=Local`,
		DefaultStringSize:         191,
		SkipInitializeWithVersion: false,
	}

	db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	//自定义连接
	//db, err := gorm.Open(mysql.New(mysql.Config{
	//DriverName: "postgres",
	//DSN:        `root:!QAZ2wsx@tcp(60.205.194.87:3306)/gulimall?charset=utf8mb4&parseTime=True&loc=Local`,
	//}), &gorm.Config{})
	//
	//if err != nil {
	//panic(err)
	//}

	//查找全部记录
	ps := make([]PmsCategory, 16)
	db.Debug().Table("pms_category").Limit(5).Find(&ps)
	fmt.Println(ps)

	//查找一条记录  并排序
	p := PmsCategory{}
	db.Debug().Table("pms_category").Order("cat_id  desc").First(&p)
	fmt.Println(p)

	//where  条件
	db.Debug().Table("pms_category").Where("name like  ?", "%电脑%").Find(&p)
	fmt.Println(p)
	// struct & 指定特定字段

	db.Debug().Table("pms_category").Where(&PmsCategory{Name: "手机", ProductUnit: "fewfewfgew"}, "product_unit").Find(&p)
	fmt.Println(p)
	//  map

	db.Debug().Table("pms_category").Where(map[string]interface{}{"name": "数码"}).Find(&p)
	fmt.Println(p)

	//原生sql
	db.Debug().Raw("select  *  from  pms_category pc inner join pms_category_brand_relation  pcbr on pc.cat_id = pcbr.catelog_id  where name  = ?", "手机").Scan(&p)

	fmt.Println(p)
	var count int64
	db.Debug().Table("pms_category").Group("sort").Having("count(*)>?", 2).Count(&count)

	fmt.Println(count)
	db.Debug().Preload("pms_category").Preload("pms_category_brand_relation ").Find(&ps)

}
